package day12.convertedstream;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author Xiao
 * @date 2021/8/2
 */
public class ConvertedStreamDemo01 {
    /**
     * 转换流如何使用
     * 	1.创建读和写的流对象,可以指定编码,不指定默认是utf-8
     * 		InputStreamReader(InputStream in)
     * 		InputStreamReader(InputStream in, String charsetName)
     * 		OutputStreamWriter(OutputStream out)
     * 		OutputStreamWriter(OutputStream out, String charsetName)
     * 	2.进行读和写的操作
     * 		读: read(char[] cbuf)
     * 		写: write(String str)
     * 	3.关流,释放资源
     * 		 close()
     */
    public static void main(String[] args) throws IndexOutOfBoundsException, IOException {
        //method1();
        //method2();
        //method3();
        FileReader fr = new FileReader("E:\\develop\\Test\\a02.txt", Charset.forName("gbk"));
        int read;
        while ((read = fr.read()) != -1) {
            System.out.println((char)read);
        }
        fr.close();
    }

    private static void method3() throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(
                new FileOutputStream("E:\\develop\\Test\\a03.txt"),"UTF-8");
        osw.write("我爱学习，学习使我快乐！");
        osw.flush();
        osw.close();
    }

    private static void method2() throws IOException {
        InputStreamReader isr = new InputStreamReader(
                new FileInputStream("E:\\develop\\Test\\a02.txt"), "gbk");
        int read;
        while ((read = isr.read()) != -1) {
            System.out.println((char)read);
        }
        isr.close();
    }

    /**
     * a02.txt为系统默认的编码格式ANSI，
     * windows中默认编码格式为GBK，IDEA默认编码格式为UTF-8
     * 两者不一致，所以会导致乱码
     * */
    private static void method1() throws IOException {
        FileReader fr = new FileReader("E:\\develop\\Test\\a02.txt");
        int read;
        while ((read = fr.read()) != -1) {
            System.out.println((char)read);
        }
        fr.close();
    }
}
